package com.hzlj.position.config.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.fz.common.base.exception.PubException;
import com.fz.common.dict.annotation.DictConvert;
import com.fz.common.redis.annotation.SyncLock;
import com.hzlj.position.config.cache.JzJbxxConfigCache;
import com.hzlj.position.config.common.dto.jzJbxxConfig.JzJbxxConfigQueryResultDTO;
import com.hzlj.position.config.common.dto.jzJbxxConfig.JzJbxxConfigUpdateDTO;
import com.hzlj.position.config.common.model.JzJbxxConfig;
import com.hzlj.position.config.converter.JzJbxxConfigConverter;
import com.hzlj.position.config.dao.JzJbxxConfigDao;
import com.hzlj.position.config.service.JzJbxxConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 矫正-基本信息-配置(JzJbxxConfig)表服务接口
 *
 * @author lifh
 * @date 2023-03-29 13:50:02
 */
@Slf4j
@Service
public class JzJbxxConfigServiceImpl implements JzJbxxConfigService {
    @Resource
    private JzJbxxConfigDao jzJbxxConfigDao;
    @Resource
    private JzJbxxConfigCache jzJbxxConfigCache;

    /**
     * 通过jzId查询单条数据
     */
    @Override
    @DictConvert
    public JzJbxxConfigQueryResultDTO getJzJbxxConfigByJzId(String jzId) {
        return jzJbxxConfigCache.getJzJbxxConfigByJzId(jzId);
    }


    /**
     * 修改数据
     *
     * @param dto 实例对象
     * @return 实例对象
     */
    @Override
    @SyncLock(key = "#dto.id")
    @Transactional(rollbackFor = Exception.class)
    public boolean updateJzJbxxConfig(JzJbxxConfigUpdateDTO dto) {
        if (ObjectUtil.isEmpty(dto.getId())) {
            throw new PubException("请传入矫正ID");
        }
        JzJbxxConfig exists = this.jzJbxxConfigDao.getById(dto.getId());
        JzJbxxConfig upsert = JzJbxxConfigConverter.from(dto);
        try {
            //新增
            if (ObjectUtil.isEmpty(exists)) {
                this.jzJbxxConfigDao.save(upsert);
                log.info("【新增数据成功】:jzJbxxConfig={}", upsert);
                return true;
            }

            boolean update = this.jzJbxxConfigDao.updateJzJbxxConfig(upsert);
            if (update) {
                removeCache(dto.getId());
                log.info("【更新数据成功】:jzJbxxConfig={}", upsert);
            }
            return update;
        } finally {
            removeCache(dto.getId());
        }

    }

    private void removeCache(String jzId) {
        jzJbxxConfigCache.remove(jzId);
    }
}
